<script lang="ts">
    import { onMount } from 'svelte';
    // import { get, post } from '../../utils/api';
    // import { addToast } from '../../stores/toastStore';
    import Header from '../../../components/common/Header.svelte';

    let content = '';
    let eventSource;

    onMount(() => {
    });

    function startRequest() {
        eventSource = new EventSource('http://localhost:8080/response/sse');

        eventSource.onmessage = (event) => {
            console.log("sse: ", event.data);
            if (event.data!='[DONE]') {
                const data = JSON.parse(event.data);
                content += data.choices[0].delta.content;
            }
        };
        eventSource.onerror = () => {
            console.error('SSE 失败');
            eventSource.close();
        };

        return () => {
            eventSource.close();
        };
    }
    function stopRequest() {
        if (eventSource) {
            eventSource.close();
        }
    }
</script>

<main>
    <Header />
    <div class="flex px-8 py-4 space-x-8">
        <div class="flex-1 bg-white rounded shadow p-4">
            <div class="flex space-x-4 mb-4">
                <button class="bg-gray-200 rounded-full px-4 py-2" on:click={startRequest}>开始</button>
                <button class="bg-gray-200 rounded-full px-4 py-2" on:click={stopRequest}>结束</button>
            </div>
            <textarea class="w-full h-64 border rounded p-2" placeholder="请输入文本...">{content}</textarea>
            <div class="text-right text-gray-500 mt-2">0/1000</div>
        </div>     
    </div>
</main>
